#include "bucquage.h"
#include "ui_bucquage.h"

Bucquage::Bucquage(Pg *p, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Bucquage)
{
    ui->setupUi(this);
    pg = p;

    QSettings s;
    tactile = s.value("tactile").toString() == "OUI" ? true : false;
    gestionStocks = s.value("gestionstock").toString() == "OUI" ? true : false;

    if(tactile){
        clavier = new Clavier(this);
        ui->verticalLayout->addWidget(clavier);
    }

    db = QSqlDatabase::database();



    connect(ui->listChoisi,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(retirerConso(QListWidgetItem*)));
    connect(ui->listDispo,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(ajouterConso(QListWidgetItem*)));

    ui->labelBucque->setText(pg->getBucque());
    ui->spinAvoir->setValue(pg->getSolde());
    ui->spinInit->setValue(pg->getSolde());

    couleurNeg.setColor(QPalette::Text,QColor("red"));
    couleurPos.setColor(QPalette::Text,QColor("green"));

    recherche = "";

    majChoix();
    majListeConso();

    this->setFocus();
}

Bucquage::~Bucquage()
{
    delete ui;
    delete pg;
}

void Bucquage::on_ButtonAnnuler_clicked(){
    this->close();
}

void Bucquage::on_ButtonBucquer_clicked(){
    db.transaction();

    QSqlQuery q2;
    q2.prepare("UPDATE `Consos` SET Dispo = Dispo - :qte WHERE `Intitule` = :int");

    QSqlQuery q;
    q.prepare("INSERT INTO `Historique` ( `Pg` , `Conso` , `Date` ) VALUES ( :id, ( SELECT `Id` FROM `Consos` WHERE `Intitule` = :intitule AND Actif = 1), NOW() ) ");
    q.bindValue(":id",pg->getId());
    for(int k = 0 ; k < consos.length() ; k++)
    {
        q.bindValue(":intitule",consos.at(k));
        for(int i = 0 ; i < nbConsos.at(k); i++)
        {
            q.exec();
        }

        if(gestionStocks){
            q2.bindValue(":int",consos.at(k));
            q2.bindValue(":qte",nbConsos.at(k));
            q2.exec();
        }


    }
    q.prepare("UPDATE `Pg` SET `Solde` = :solde WHERE `Id` = :id");
    q.bindValue(":id",pg->getId());
    q.bindValue(":solde",ui->spinAvoir->value());
    q.exec();

    db.commit();

    emit termine();
    this->close();
}

void Bucquage::keyPressEvent(QKeyEvent *e)
{
    //QMessageBox::information(this,"",QString::number(e->key()));
    this->setFocus();
    if(e->key() >= Qt::Key_A && e->key() <= Qt::Key_Z)
    {
        recherche += e->text();
    }else if(e->key() == Qt::Key_Backspace){
        recherche = "";
    }else if(e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter ){
        //QMessageBox::information(this,"Key","Enter");
        on_ButtonBucquer_clicked();
    }else if(e->key() == Qt::Key_Escape){
        on_ButtonAnnuler_clicked();
    }else if(e->key() >= Qt::Key_F1 && e->key() < Qt::Key_F13){
        int i = e->key()- Qt::Key_F1;
        if(e->modifiers() == Qt::NoModifier){
            if(i < ui->listDispo->count())
                ajouterConso(ui->listDispo->item(i));
        }else if(e->modifiers() == Qt::ControlModifier){
            if(i < ui->listChoisi->count())
                retirerConso(ui->listChoisi->item(i));
        }
    }
    majListeConso();
}

void Bucquage::majListeConso(){
    ui->listDispo->clear();

    QStringList l = Statistiques::consoMax(recherche,pg->getId());

    for(int i=0; i< l.count(); i++){
            QString s;
            if(!tactile && i<12){
                s += "F"+QString::number(i+1)+"| " ;
            }
            s += l.at(i);
            ui->listDispo->addItem(s);
    }

}

void Bucquage::ajouterConso(QListWidgetItem *it){
    QString s = it->text();
    if(!tactile){
        s = s.split("| ").at(1);
    }
    QStringList l = s.split(" : ");

    if(consos.contains(l.at(0)))
    {
        int k = consos.indexOf(l.at(0));
        nbConsos.replace(k,nbConsos.at(k) + 1);
    }else{
        consos.append(l.at(0));
        nbConsos.append(1);
        prixConsos.append(l.at(1).toDouble());
    }
    majChoix();

}

void Bucquage::majChoix(){
    ui->listChoisi->clear();
    for(int i = 0 ; i<consos.length() ; i++){
        QString s;
        if(!tactile && i<12){
            s+= "F"+QString::number(i+1)+"| ";
        }
        s+= QString::number(nbConsos.at(i))+ " x " +consos.at(i);

        ui->listChoisi->addItem(s);
    }

    double tot = 0.0;
    for(int i =0;i<prixConsos.count();i++){
        tot += prixConsos.at(i) * nbConsos.at(i);
    }

    ui->spinTotal->setValue(tot);
    ui->spinAvoir->setValue(pg->getSolde() - tot);

    if(ui->spinAvoir->value() < 0){
        ui->spinAvoir->setPalette(couleurNeg);
    }else{
        ui->spinAvoir->setPalette(couleurPos);
    }

    if(ui->spinInit->value() < 0){
        ui->spinInit->setPalette(couleurNeg);
    }else{
        ui->spinInit->setPalette(couleurPos);
    }

    this->setFocus();
}

void Bucquage::retirerConso(QListWidgetItem *it){

    QString s = it->text();
    if(!tactile){
        s = s.split("| ").at(1);
    }
    QStringList l = s.split(" x ").at(1).split(" : ");
    int k = consos.indexOf(l.at(0));
    if(nbConsos.at(k) > 1){
        nbConsos.replace(k,nbConsos.at(k)-1);
    }else{
        consos.removeAt(k);
        nbConsos.removeAt(k);
        prixConsos.removeAt(k);
    }
    majChoix();
}
